package com.itheima.service.imp;

import com.itheima.DTO.Login;
import com.itheima.common.constant.MessageConstant;
import com.itheima.mapper.MemberMapper;
import com.itheima.pojo.Member;
import com.itheima.service.MemberService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class MemberServiceImp implements MemberService {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private MemberMapper memberMapper;

    public String login(Login loginDTO) {
        // 获取用户输入的验证码
        String validateCode = loginDTO.getValidateCode();

        // 检查 loginDTO 是否为 null
        if (loginDTO == null || loginDTO.getTelephone() == null || validateCode.trim().isEmpty()) {
            log.error("LoginDTO is null");
            throw new IllegalArgumentException(MessageConstant.TELEPHONE_VALIDATECODE_NOTNULL);
        }
        //1.校验用户输入的短信验证码是否正确，如果验证码错误则登录失败
        if (!validateCode.equals(redisTemplate.opsForValue().get(loginDTO.getTelephone()))) {
            log.error("验证码输入错误");
            return MessageConstant.VALIDATECODE_ERROR;
        }
        //2.则判断当前用户是否为会员，如果不是会员则自动完成会员注册
        Member member = memberMapper.getMember(loginDTO);
        log.info("查询到的用户为{}", member);
        if (member != null){
            return MessageConstant.LOGIN_SUCCESS;
        }else {

            //3.登录成功,创建用户
            memberMapper.addOneMember(loginDTO);
            return MessageConstant.LOGIN_SUCCESS;
        }

    }
}
